<?php

namespace app\admin\controller\vip;

use app\admin\model\Level;
use app\common\controller\Backend;
use app\common\manager\PlatformManager;
use app\common\model\Goods;
use app\common\model\Platform\Log;
use app\common\model\User;
use app\common\model\VipExpires;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * vip过期管理
 *
 * @icon fa fa-circle-o
 */
class Expires extends Backend
{

    /**
     * VipExpires模型对象
     * @var \app\admin\model\VipExpires
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\VipExpires;

    }


    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $userId = $this->request->param("ids");
        $uid = $this->request->param("uid");
        if (false === $this->request->isAjax()) {
            $this->assign('userId',$userId);
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where(function ($query) use ($uid) {
                if ($uid){
                    $query->where('user_id', $uid);
                }
            })
            ->order($sort, $order)
            ->paginate($limit);
        if ($list){
            foreach ($list as &$row){
                $levelInfo = Level::where('vl_id',$row->level)->find();
                $row->levelName = $levelInfo['vip_name'] ?? '';
            }
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add()
    {
        $uid = $this->request->param("uid");
        if (false === $this->request->isPost()) {
            $this->assign('userId',$uid);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $goodsInfo = Goods::where('g_id',$params['goods_id'])->find();
            if (!$goodsInfo){
                throw new Exception('当前商品信息不存在');
            }
            $levelInfo = \app\common\model\Level::where('vl_id',$goodsInfo['level_id'])->find();
            if (!$levelInfo){
                throw new Exception('当前订单等级信息不存在');
            }
            $vipExpiresInfo = VipExpires::where('user_id',$params['user_id'])->where('level',$levelInfo['vl_id'])->find();
            $result = false;
            $startTime = strtotime(date('Y-m-d'));
            if(!$vipExpiresInfo){
                $insert = [
                    'user_id'=>$params['user_id'],
                    'level'=>$levelInfo['vl_id'],
                    'level_sort'=>$levelInfo['sort'],
                    'start_date'=>$startTime,
                    'end_date'=>$startTime+($goodsInfo['validity_period']*3600*24),
                    'create_time'=>time(),
                ];
                $result = VipExpires::create($insert);
            }else{
                $result = VipExpires::where('user_id',$params['user_id'])->where('level',$levelInfo['vl_id'])->update([
                    'end_date'=>Db::raw('end_date + '.($goodsInfo['validity_period']*3600*24))
                ]);
            }

            if (!$result){
                throw new Exception('当前订单更新失败');
            }
            $vipUser = VipExpires::where('user_id',$params['user_id'])->order('level_sort desc')->find();
            if(!User::where('id',$params['user_id'])->update([
                'temp_level'=>$vipUser['level'] ?? $levelInfo['vl_id'],
                'updatetime'=>time(),
            ])){
                throw new Exception('用户信息更新失败');
            }

            $money = bcadd($goodsInfo['price'],0,2);
            $resultPlatform = PlatformManager::platformLog($money,date('Y-m-d H:i:s',time()),Log::DIRECTIVE_OUT,Log::TYPE_SYS_VIP_PRESENT,['recipient'=>$params['user_id']],false);
            if ($resultPlatform['code']!=PlatformManager::$successCode){
                throw new Exception($resultPlatform['message']);
            }
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function del($ids='')
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
                $vipUser = \app\common\model\VipExpires::where('user_id',$item->user_id)->order('level_sort')->find();
                if(!User::where('id',$item->user_id)->update([
                    'temp_level'=>$vipUser['level'] ?? 0,
                    'updatetime'=>time(),
                ])){
                    throw new Exception('用户信息更新失败');
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
